<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;

class AuthController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:a', ['except' => ['login']]);
    }

    public function login()
    {
        $credentials = request(['mobile', 'password']);

        if (!$token = auth('a')->attempt($credentials)) {
            return response()->json(
            [
                'status_code' => 401,
                'message'     => '账号或密码错误，请检查后重试.'
            ], 401);
        }
        $userInfo = auth('a')->user();
        if ($userInfo)
        {
            $userInfo = User::query()->with(['member'])->find($userInfo->id);
        }

        return response()->json([
            'status_code' => 200,
            'message'     => '登录成功.',
            'result'      => [
                'user_info'    => $userInfo,
                'access_token' => $token,
                'token_type'   => 'bearer',
                'expires_in'   => auth('a')->factory()->getTTL() * 60
            ]
        ]);
    }

    public function me()
    {
        $userInfo = auth('a')->user();

        return response()->json([
            'status_code' => 200,
            'message'     => '请求成功.',
            'result'      => $userInfo
        ]);
    }

    public function logout()
    {
        auth('a')->logout();
        return response()->json([
            'status_code' => 200,
            'message' => '退出成功.'
        ]);
    }

    public function refresh()
    {
        $token = auth('a')->refresh();
        return $this->respondWithToken($token,'登录令牌刷新成功.');
    }

    protected function respondWithToken($token,$msg = null)
    {
        return response()->json([
                'status_code' => 200,
                'message'     => $msg ?? '请求成功.',
                'result'      => [
                    'access_token' => $token,
                    'token_type' => 'bearer',
                    'expires_in' => auth('a')->factory()->getTTL() * 60
                ]
            ]);
    }

}
